package chunmap.service.gmap;

import java.io.IOException;
import java.io.PrintStream;
import java.nio.charset.Charset;
import java.util.List;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import chunmap.app.tools.SelectIterator;
import chunmap.data.feature.FeatureUtil;
import chunmap.model.elem.Envelope;
import chunmap.service.Util;
import chunmap.view.layer.Layer;
import chunmap.view.layer.VectorLayer;

public class GetFeatureInfo {
	protected String layer;
	private List<Layer> layers;

	public GetFeatureInfo(List<Layer> layers) {
		this.layers = layers;
	}

	public void service(HttpServletRequest request, HttpServletResponse response)
			throws ServletException, IOException {
		layer = request.getParameter("QUERY_LAYER");
		PrintStream out = new PrintStream(response.getOutputStream());

		String bbox = request.getParameter("BBOX");
		Envelope envelop = parseEnvelop(bbox);

		String s = select(envelop);
		out.write(s.getBytes(Charset.forName("UTF-8")));
	}

	private Envelope parseEnvelop(String bbox) {
		String[] ss = bbox.split(",");
		double minx = Double.valueOf(ss[0]);
		double miny = Double.valueOf(ss[1]);
		double maxx = Double.valueOf(ss[2]);
		double maxy = Double.valueOf(ss[3]);

		Envelope envelop = new Envelope(minx, miny, maxx, maxy);
		return envelop;
	}

	private String select(Envelope envelop) {

		SelectIterator it = new SelectIterator(envelop);
		List<Layer> layers = getLayers();
		// Log.log(Logger.Debug, "layer size " + layers.size());
		for (Layer layer : layers) {
			if (layer instanceof VectorLayer) {
				VectorLayer vl = (VectorLayer) layer;
				if (vl.isSelectabel()) {
					vl.getFeatures().select(envelop, it);
				}
			}
		}
		// Log.log(Logger.Debug, "selected feature size " + it.features.size());
		String s = FeatureUtil.LayerHeadString(it.features, envelop).toString();
		return s;
	}

	private List<Layer> getLayers() {
		if (layer == null) {
			return layers;
		} else {
			return Util.getLayersByName(layers, layer);
		}
	}
}
